package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
)

var (
	currentPort = "12581"
	configFile  = "config.txt"
)

func main() {
	log.Println("Starting Movie Tool...")

	loadConfig()
	os.MkdirAll("assets/uploads", 0755)
	os.MkdirAll("files", 0755)

	go restartServerLoop()

	startTray()
}

func loadConfig() {
	if _, err := os.Stat(configFile); os.IsNotExist(err) {
		saveConfig()
		return
	}

	file, err := os.Open(configFile)
	if err != nil {
		return
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if strings.HasPrefix(line, "port=") {
			port := strings.TrimPrefix(line, "port=")
			if port != "" {
				currentPort = port
			}
			break
		}
	}
}

func saveConfig() {
	content := fmt.Sprintf("port=%s\n", currentPort)
	os.WriteFile(configFile, []byte(content), 0644)
}

func setPort(port string) {
	if portNum, err := strconv.Atoi(port); err != nil || portNum < 1 || portNum > 65535 {
		log.Printf("Invalid port: %s", port)
		return
	}
	currentPort = port
	saveConfig()
}

func getCurrentPort() string {
	return currentPort
}

func addFirewallException() {
	if runtime.GOOS != "windows" {
		return
	}

	execPath, _ := os.Executable()
	
	cmd := exec.Command("netsh", "advfirewall", "firewall", "add", "rule", 
		fmt.Sprintf("name=MovieTool_Port_%s", currentPort), 
		"dir=in", 
		"action=allow", 
		"program="+execPath,
		"profile=private,domain,public",
		fmt.Sprintf("localport=%s", currentPort),
		"protocol=TCP")
	
	cmd.Run()
}

func manualAddFirewall() {
	if runtime.GOOS != "windows" {
		return
	}

	execPath, _ := os.Executable()
	
	scriptContent := fmt.Sprintf(`
# MovieTool 防火墙规则添加脚本
New-NetFirewallRule -DisplayName "MovieTool Port %s" -Direction Inbound -Program "%s" -Profile Private,Domain,Public -LocalPort %s -Protocol TCP -Action Allow
Write-Host "防火墙规则已添加成功！"
Pause
`, currentPort, execPath, currentPort)

	scriptPath := filepath.Join(os.TempDir(), "add_firewall_rule.ps1")
	os.WriteFile(scriptPath, []byte(scriptContent), 0644)

	cmd := exec.Command("powershell", "-Command", fmt.Sprintf("Start-Process powershell -ArgumentList '-ExecutionPolicy Bypass -File \"%s\"' -Verb RunAs", scriptPath))
	cmd.Run()
}